package org.geektimes.serialize.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.geektimes.serialize.SerializeException;

import java.io.IOException;

/**
 * @author karidyang
 */
public class JsonSerializer<T> extends AbstractSerializer<T> {


    @Override
    public byte[] doSerialize(T t) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {

            return objectMapper.writeValueAsBytes(t);

        } catch (JsonProcessingException e) {
            throw new SerializeException(e);
        }
    }

    @Override
    public T doDescrialize(byte[] bytes, Class<T> typeClass) {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.readValue(bytes, typeClass);
        } catch (IOException e) {
            throw new SerializeException(e);
        }

    }



}
